﻿using System.Collections.Generic;
using System.Windows;

namespace POBR.ImageProcessor
{
	public class Segmentator
	{
		public IEnumerable<Int32Rect> DivideIntoSegments(Picture picture)
		{
			var clone = picture.Clone();
			var result = new List<Int32Rect>();

			for (var segment = FindSegment(clone); !segment.IsEmpty; segment = FindSegment(clone))
				result.Add(segment);

			return result;
		}

		private Int32Rect FindSegment(Picture picture)
		{
			for (int x = 0; x != picture.Width; ++x)
			{
				for (int y = 0; y < picture.Height; ++y)
				{
					if (picture.IsRed(x, y))
					{
						var xMin = x;
						var xMax = x;
						var yMin = y;
						var yMax = y;

						SetSegmentCoordinates(picture, x, y, ref xMin, ref xMax, ref yMin, ref yMax);

						return new Int32Rect(xMin, yMin, xMax - xMin, yMax - yMin);
					}
				}
			}

			return new Int32Rect();
		}

		private void SetSegmentCoordinates(Picture picture, int x, int y, ref int xMin, ref int xMax, ref int yMin, ref int yMax)
		{
			if (false == picture.IsRed(x, y))
				return;

			picture.SetBlack(x, y);

			if (x < xMin) xMin = x;
			if (x > xMax) xMax = x;
			if (y < yMin) yMin = y;
			if (y > yMax) yMax = y;

			var checkLeft = x > 0;
			var checkRight = x < picture.Width - 1;
			var checkBottom = y > 0;
			var checkTop = y < picture.Height - 1;

			if (checkLeft)
				SetSegmentCoordinates(picture, x - 1, y, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkRight)
				SetSegmentCoordinates(picture, x + 1, y, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkBottom)
				SetSegmentCoordinates(picture, x, y - 1, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkTop)
				SetSegmentCoordinates(picture, x, y + 1, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkLeft && checkBottom)
				SetSegmentCoordinates(picture, x - 1, y - 1, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkLeft && checkTop)
				SetSegmentCoordinates(picture, x - 1, y + 1, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkRight && checkBottom)
				SetSegmentCoordinates(picture, x + 1, y - 1, ref xMin, ref xMax, ref yMin, ref yMax);
			if (checkRight && checkTop)
				SetSegmentCoordinates(picture, x + 1, y + 1, ref xMin, ref xMax, ref yMin, ref yMax);
		}
	}
}
